package juc.c_021_02Interview;
/*
   Talk is cheap. Show me the code.
 */

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * @Description 面试题
 * 写一个具有10容量的容器支持两个线程的阻塞调用
 * @Date 2021/6/26
 * @Author liudl
 */
public class MyContainer1<T> {
    final private LinkedList<T> lists = new LinkedList<>();

    public synchronized void put(T t) {
        int MAX = 10;
        while (lists.size() == MAX) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        lists.add(t);
        this.notifyAll();
    }

    public synchronized T get() {
        T t = null;
        while (lists.size() == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t = lists.removeFirst();
        this.notifyAll();
        return t;
    }

    public static void main(String[] args) {
        MyContainer1<String> c = new MyContainer1<>();
        for(int i=0; i<10; i++) {
            new Thread(()->{
                for(int j=0; j<5; j++) System.out.println(c.get());
            }, "c" + i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for(int i=0; i<2; i++) {
            new Thread(()->{
                for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j);
            }, "p" + i).start();
        }
    }
}
